<template>
  <div>
    <el-upload
      action="#"
      :file-list="fileList"
      list-type="picture-card"
      :http-request="upload"
      :on-remove="onRemove"
      :on-change="onChange"
      :before-upload="beforeUpload"
      :class="{disabled:fileList.length === limit}"
    >
      <i class="el-icon-plus" />
    </el-upload>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
const cos = new COS({
  SecretId: 'AKID1rRknZ4IFwNXQ4RXMwFHG0UheKkuoRou',
  SecretKey: 'rRkmZ5KJ3XkhOoxqSnrfCSR9akdFciY7'
})
export default {
  props: {
    limit: {
      type: Number,
      default: 1
    }
  },
  data() {
    return {
      fileList: []
    }
  },
  methods: {
    // 覆盖默认的上传行为,点击加号之后触发
    upload(params) {
      cos.putObject({
        Bucket: 'hr-hzy-1313460522', /* 必须 */
        Region: 'ap-guangzhou', /* 存储桶所在地域，必须字段 */
        Key: params.file.name, /* 必须 */
        StorageClass: 'STANDARD',
        Body: params.file // 上传文件对象
      }, (err, data) => {
        console.log(err || data)
        if (!err) {
          this.fileList.forEach(image => {
            if (image.uid === params.file.uid) {
              image.url = 'http://' + data.Location
              image.status = 'success'
            }
          })
        } else {
          console.log('上传失败', err)
        }
      })
    },
    // 删除图片
    onRemove(file, newFileList) {
      // file是删除的文件，newFileList是删除后的新数组
    //   console.log('删除', file, newFileList)
    // 删除后的文件列表是onRemove里面第二个参数
      this.fileList = newFileList
    },
    // 改变
    onChange(file, newFileList) {
      this.fileList = newFileList
    },
    // 上传图片前，用于校验
    beforeUpload(file) {
      const maxSize = 1024 * 1024
      if (file.siez > maxSize) {
        this.$message.error('图片需要在1M以内')
        return false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.disabled {
  ::v-deep .el-upload--picture-card {
    display: none;
  }
}
</style>
